package com.ch.service.impl;

import com.ch.dao.GoodsDao;
import com.ch.dao.SaleDao;
import com.ch.domain.Goods;
import com.ch.domain.Sale;
import com.ch.execp.NotEnoughException;
import com.ch.service.BuyGoodsService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author chenhong
 * @version 1.0.0
 * @ClassName BuyGoodsServiceImpl.java
 * @Description TODO
 * @createTime 2020年12月13日 19:38:00
 */
public class BuyGoodsServiceImpl implements BuyGoodsService {
    private SaleDao saleDao;
    private GoodsDao goodsDao;

    public void setSaleDao(SaleDao saleDao) {
        this.saleDao = saleDao;
    }

    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

    @Override
    public void buyGoods(Integer gid, Integer nums) {
        System.out.println("=======buy方法的开始");
        //记录销售信息 向sale表添加记录
        Sale sale = new Sale();
        sale.setGid(gid);
        sale.setNums(nums);
        saleDao.insertSale(sale);
        //更新库存
        Goods goods = goodsDao.selectGoods(gid);
        if(goods == null){
            throw new NullPointerException("编号为" + gid + "的商品不存在");
        }else if(goods.getAmount() < nums){
            throw new NotEnoughException("编号为" + gid + "的商品库存不足");
        }
        System.out.println("要购买的商品信息"+goods);
        Goods buyGoods = new Goods();
        buyGoods.setId(gid);
        buyGoods.setAmount(nums);
        goodsDao.updateGoods(buyGoods);

        System.out.println("=======buy方法的结束");

    }
}
